#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "err.hpp"

using namespace std;

class Sock
{
    static const int backlog = 32;

public:
    // 创建套接字
    static int Socket()
    {
        // _sock = socket(AF_INET, SOCK_STREAM, 0);
        int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (sockfd < 0)
        {
            logMessage(FATAL, "create socket err!");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "create socket success!");

        // 设置地址复用
        int opt = 1;
        setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(&opt));
        return sockfd;
    }

    // 2.绑定网络信息
    static void Bind(int sockfd, uint16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = PF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY; // 绑定任意IP
        if (bind(sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind socket err!");
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "bind socket success!");
    }

    // 3.设置socket为监听状态
    static void Listen(int sockfd)
    {
        if (listen(sockfd, backlog) < 0) // 第二个参数后面再学
        {
            logMessage(FATAL, "listen socket err!");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL, "listen socket success : %d!", sockfd);
    }

    // 4.获取新链接(注意：获取的前提是链接已经存在)
    // accept的返回值sock，将来才是和client通信的fd
    static int Accept(int listenSock, std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sock = accept(listenSock, (struct sockaddr *)&peer, &len);
        if (sock < 0)
        {
            logMessage(ERROR, "accept error, next!");
        }
        else
        {
            logMessage(NORMAL, "accept a new link success! get new sockfd : %d", sock);
            *clientip = inet_ntoa(peer.sin_addr);
            *clientport = ntohs(peer.sin_port);
        }
        return sock;
    }
};